package com.myblog.service;

import com.myblog.mapper.CategoryMapper;
import com.myblog.entity.Category;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@CacheConfig(cacheNames = "BLOG:SESSION_KEY_IN_CATEGORY")
public class CategoryServiceImpl implements CategoryService {
    @Autowired
    CategoryMapper categoryMapper;

    @Cacheable(key = "'LIST_P'+ #page +'L'+ #limit")
    @Override
    public List<Category> list() {
        return categoryMapper.list();
    }

    @Cacheable(key = "'CID' +#id")
    @Override
    public Category listByCid(Integer id) {
        return categoryMapper.listByCid(id);
    }

    //    @CachePut(key = "#result.id")
    @CacheEvict(allEntries = true) //此注解会清除cacheNames下所有缓存
    @Override
    public void save(Category category) {
        //更新
        if (category.getId() != null) {
            categoryMapper.updateById(category);
        } else {
            //保存
            categoryMapper.insert(category);
        }
    }

    @CacheEvict(allEntries = true) //此注解会清除cacheNames下所有缓存
    @Override
    public void del(Integer id) {
        categoryMapper.deleteById(id);
    }

    @Cacheable(key = "'total'", unless = "#result == null")
    @Override
    public Integer total() {
        return categoryMapper.total();
    }
}
